<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <el-tabs v-model="tabType" type="card" @tab-click="handleClick">
        <el-tab-pane label="物料申购" name="0"></el-tab-pane>
        <el-tab-pane label="教具申购" name="1"></el-tab-pane>
      </el-tabs>
      <el-tabs v-model="tabStatus" type="card" @tab-click="handleClickStatus">
        <el-tab-pane :label="item.name" :name="item.id.toString()" v-for="item in statusLine"
                     :key="item.id"></el-tab-pane>
      </el-tabs>
      <div class="toplineBox mb-10">
        <div class="toplineBox-left">
          <el-input v-model="searchData.name" placeholder="名称" size="small" class="w-140 mr-10"></el-input>
          <el-input v-model="searchData.user_name" placeholder="申请人" size="small" class="w-80 mr-10"></el-input>
          <el-date-picker
              v-model="addtime"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              class="mr-10">
          </el-date-picker>
          <el-button type="primary" size="small" @click="searchFn(1)"><i class="el-icon-search"></i>搜索</el-button>
          <el-button size="small" @click="searchFn(2)"><i class="el-icon-refresh"></i>重置</el-button>
        </div>
        <!--        <p class="numberline toplineBox-right">总{{ page.total }}条</p>-->
      </div>
      <div class="toplineBox mb-10">
        <el-button type="primary" size="small" @click="examinBtn(3)" plain
                   :disabled="multipleSelection.length?false:true">批量通过
        </el-button>
        <el-button type="danger" size="small" @click="examinBtn(4)" plain
                   :disabled="multipleSelection.length?false:true">批量驳回
        </el-button>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <el-table
              ref="multipleTable"
              :data="arryList"
              :stripe="tableStyle.tableStripe"
              :border="tableStyle.tableBorder"
              tooltip-effect="dark"
              header-cell-class-name="table-text-c"
              style="width: 100%"
              @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                width="50"
                align="center"
                :key="1"
                :selectable="selectable"
            >
            </el-table-column>
            <!--            <el-table-column-->
            <!--                prop="id"-->
            <!--                label="ID"-->
            <!--                align="center"-->
            <!--                :key="2">-->
            <!--            </el-table-column>-->
            <el-table-column
                prop="name"
                :label="Number(searchData.type)==0?'物料名称':'教具名称'"
                width="120"
                align="center"
                :key="2">
            </el-table-column>
            <el-table-column
                prop="need_number"
                label="数量"
                align="center"
                :key="3">
              <template slot-scope="scope">
                <el-link type="danger" v-if="scope.row.status_user == 0"
                         @click="editDetailFn(scope.row, 'need_number')">
                  {{ scope.row.need_number }}
                  <i class="el-icon-edit-outline priceLine"></i>
                </el-link>
                <span v-else>
                  {{ scope.row.need_number }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
                label="单价"
                align="center"
                prop="price"
                :key="4">
              <template slot-scope="scope">
                <el-link type="danger" v-if="scope.row.status_user == 0" @click="editDetailFn(scope.row, 'price')">
                  {{ scope.row.price }}
                  <i class="el-icon-edit-outline priceLine"></i>
                </el-link>
                <span v-else>
                  {{ scope.row.price }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
                prop="url"
                label="采购网址"
                align="center"
                show-overflow-tooltip
                :key="5">
              <template slot-scope="scope">
                <el-link type="danger" v-if="scope.row.status_user == 0" @click="editDetailFn(scope.row, 'url')">
                  <span style="width: 100px;overflow: hidden;display: block;">{{ scope.row.url }}</span>
                  <i class="el-icon-edit-outline priceLine"></i>
                </el-link>
                <span v-else>
                  {{ scope.row.url }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
                prop="url"
                label="资金来源"
                align="center"
                show-overflow-tooltip
                :key="6">
              <template slot-scope="scope">
                <el-link type="danger" v-if="scope.row.status_user == 0" @click="editDetailFn(scope.row, 'finance_source')">
                  <span style="width: 100px;overflow: hidden;display: block;">{{ scope.row.finance_source }}</span>
                  <i class="el-icon-edit-outline priceLine"></i>
                </el-link>
                <span v-else>
                  {{ scope.row.finance_source }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
                prop="expect_time"
                label="期望交付日期"
                align="center"
                :key="7">
            </el-table-column>
            <el-table-column
                label="申请人"
                align="center"
                :show-overflow-tooltip="true"
                :key="8">
              <template slot-scope="scope">
                {{ scope.row.user ? scope.row.user.realname : '--' }}
              </template>
            </el-table-column>
            <el-table-column
                prop="create_time"
                label="申请时间"
                align="center"
                :key="9">
            </el-table-column>
            <el-table-column
                prop="reason"
                label="申请事由"
                align="center"
                :key="10">
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                align="center"
                :key="11">
              <template slot-scope="scope">
                <!--                0待审核1通过2驳回3完成-->
                <el-popover
                    placement="left-start"
                    title="审核进程"
                    width="250"
                    trigger="hover">
                  <div class="tableline">
                    <div class="list" v-for="item in scope.row.examine" :key="'l'+item.id">
                      <p v-if="!item.status">{{ item.flow_name }}：<i>{{item.user_text}}【{{ item.status_text }}】</i></p>
                      <p v-else>{{ item.flow_name }}：<i
                          :style="{color: item.status==1?'green':'red'}">{{
                          item.status == 1 ? (item.examineuser ? item.examineuser.realname + '，通过（' + getTimePut(item.update_time) + '）' : '') : (item.examineuser ? item.examineuser.realname + '，驳回(' + item.content + ')' : '')
                        }}</i></p>
                    </div>
                  </div>
                  <!--                  <span slot="reference" class="tablelineBtn">{{ !scope.row.examine_user_time ? '待审批' : '已审批' }}</span>-->

                  <el-link :underline="false" slot="reference" v-if="!scope.row.examine_user_status" type="primary">
                    待审批
                  </el-link>
                  <el-link :underline="false" v-else slot="reference"
                           :type="scope.row.examine_user_status==2?'danger':'success'">
                    {{ scope.row.examine_user_status == 2 ? '已驳回' : '已通过' }}
                  </el-link>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
                prop="examine_user_time"
                label="审核时间"
                align="center"
                :key="12">
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="100"
                :key="13">
              <template slot-scope="scope">
                <el-button size="mini" @click="godeDetail(scope.row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="page.total"
            :page-size="page.pagesize"
            @current-change="handleSizeChange">
        </el-pagination>
      </el-col>
    </div>
    <detail :detailId="detailId" :visible.sync="detailVisible" pageType="examine" @InitFn="InitFn"></detail>
    <editDetail :detailOption="detailOption" :visible.sync="detailEditVisible" @InitFn="InitFn"
                :detailType="detailType"></editDetail>
  </div>
</template>

<script>
import {pagination, tableoption} from '@/utils/util.js'
import detail from './detail'
import editDetail from "./components/editDetail";
import {mapGetters} from "vuex";

export default {
  components: {
    detail,
    editDetail
  },
  data() {
    return {
      detailEditVisible: false,
      detailOption: null,
      detailVisible: false,
      detailId: 0,
      radioStatus: 'all',
      handleSelection: [],
      arryList: [], // 页面数据列表
      // 设置table样式
      tableStyle: tableoption,
      // 设置table页面分页所需
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      number: null,
      searchData: {
        name: '',
        user_name: '',
        start_time: '',
        end_time: '',
        examine_type: '0', // 0待审核 1通过 2驳回 3未入库 4已入库
        type: '0', // 0 物料 1 教具
        p: 1
      },
      tabStatus: '0',
      value: '1',
      addtime: '',
      multipleSelection: [],
      applyDetail: '',
      tabType: '0',
      detailType: '',
      statusLine: [
        {
          id: 99,
          name: '全部'
        },
        {
          id: 0,
          name: '待审批'
        },
        {
          id: 1,
          name: '已审批'
        },
        {
          id: 2,
          name: '已驳回'
        }
      ],
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {
    this.InitFn()
  },
  methods: {
    editDetailFn(item, type) {
      this.detailType = type
      this.detailOption = JSON.parse(JSON.stringify(item))
      this.detailEditVisible = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    selectable(row, index) {
      if (!row.examine_user_status) {
        return true;
      }
    },
    handleClick(option) {
      console.log(option.name, this.searchData.type)
      if (Number(option.name) !== Number(this.searchData.type)) {
        this.searchData.type = option.name
        this.InitFn()
      }
    },
    searchFn(option) {
      this.page.pageindex = 1
      if (option === 1) {
        if (this.addtime) {
          this.searchData.start_time = this.addtime[0];
          this.searchData.end_time = this.addtime[1];
        } else {
          this.searchData.start_time = '';
          this.searchData.end_time = '';
        }
      } else {
        this.searchData.name = '';
        this.searchData.user_name = '';
        this.searchData.start_time = '';
        this.searchData.end_time = '';
        // this.searchData.examine_type = 99
        this.addtime = []
      }
      console.log('收到搜索数据：', option);
      this.InitFn()
    },
    // 初始化
    InitFn() {
      // type 2 审核人员
      // examine_type 	整型 	必填 	1 	- 	状态0待审核1已审核
      // type 	整型 	必填 	1 	- 	类型0物料1教具
      this.searchData.p = this.page.pageindex
      let dataOption = this.getJson(this.searchData)
      if (Number(dataOption.examine_type) === 99) {
        delete dataOption['examine_type']
      }
      this.$fetch(this.api.purchase.examine, dataOption).then((response) => {
        if (response.code === 0) {
          // 检查是否按键出来
          for (let item of response.list.data) {
            item.create_time = item.create_time.split(' ')[0]
            let a = item.now_examine.split(',')
            if (a.indexOf(this.userInfo.id.toString()) !== -1) {
              item.status_user = 0
            } else {
              item.status_user = 1
            }
            let status_apply = 0
            let examinStatus = true // 如果上一级有驳回了就无法进行
            // 需要查询个人的审核状态
            // 查找属于本账户的状态 this.userInfo
            for (let items of item.examine) {
              let data_ = items.user_ids.split(',').map(Number)
              if (data_.indexOf(this.userInfo.id) !== -1 && items.examine_user) {
                item.examine_user_time = items.update_time
                item.examine_user_status = items.status
              }
              if (!examinStatus) {
                item.examine_user_status = 2
              }
              if (!status_apply) {
                if (items.status === 0) {
                  items.status_text = '待审批'
                }
                if (items.status === 1) {
                  items.status_text = '已审批'
                }
                if (items.status === 2) {
                  items.status_text = '已驳回'
                  status_apply = 1
                }
              } else {
                items.status_text = '终止'
              }
              if (items.status == 2) {
                status_apply = 1
                examinStatus = false
              }
              let user_ = []
              for(let user_item of items.flow_user){
                user_.push(user_item.realname)
              }
              items.user_text = user_.join(',')
            }
          }
          this.arryList = JSON.parse(JSON.stringify(response.list.data))
          this.page.total = response.list.total
          this.number = response.number
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    examinBtn(type, id) {
      // type 1 单条通过 2 单条驳回 3 批量通过 4 批量驳回
      let that = this;
      if (type === 1 || type === 3) {
        this.$confirm('确认通过申购审批, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          that.subimitExamin(type, id)
        }).catch(() => {

        });
      } else if (type == 2 || type === 4) {
        this.$prompt('输入申购审批驳回说明', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
          // value
          that.subimitExamin(type, id, value)
        }).catch(() => {

        });
      }
    },
    changeFn() {
      this.InitFn()
    },
    handleClickStatus(tab, event) {
      if (tab.name !== this.searchData.examine_type) {
        this.page.pageindex = 1
        this.searchData.examine_type = this.tabStatus
        this.InitFn()
      }
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val
      this.InitFn()
    },
    // 搜索组件
    subimitExamin(type, id, value) {
      // option id 需要审核的ID type 类型 1 通过 2 驳回 content 理由
      // type 1 单条通过 2 单条驳回 3 批量通过 4 批量驳回
      let option = {id: id, type: type}
      if (type === 1) {
        this.putApplyReason(option)
      } else if (type === 2) {
        option.content = value;
        this.putApplyReason(option)
      } else if (type === 3 || type === 4) {
        // 需要循环请求内容
        console.log('multipleSelection:', this.multipleSelection)
        let id_ = []
        for (let item of this.multipleSelection) {
          id_.push(item.id)
        }
        this.putApplyReason('list', type, id_, 0, value)
      }
    },
    putApplyReason(option, type, list, index, content) {
      console.log('option:', option)
      // type 1 单条通过 2 单条驳回 3 批量通过 4 批量驳回
      let n = this;
      let data_ = option;
      if (option === 'list') {
        if (type === 3) {
          data_ = {id: list[index], type: 1}
        } else {
          data_ = {id: list[index], type: 2, content: content}
        }
      }
      this.$post(this.api.purchase.examineBtn, data_).then((response) => {
        if (!response.code) {
          if (option !== 'list') {
            n.$message.success(response.msg)
            n.InitFn()
          } else {
            if (index < list.length) {
              if (list[index + 1]) {
                n.putApplyReason('list', type, list, index + 1, content)
              } else {
                n.$message.success(response.msg)
                n.InitFn()
              }
            }
          }
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    godeDetail(option) {
      this.detailId = option.id;
      this.detailVisible = true;
    },
    getTimePut(option) {
      return option.split(' ')[0]
    }
  },
  mounted() {
  },
  // 缓存机制 end
}
</script>

<style scoped>
.tableline .list {
  font-size: 12px;
}

.wx-user-box-line img {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 5px;
}

.wx-user-box-line {
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-wx {
  cursor: pointer;
  padding: 5px;
}

.btn-wx:hover {
  color: #1b8de5;
  text-decoration: underline;
}

.delet-wx {
  color: red;
  cursor: pointer;
}

.delet-wx:hover {
  text-decoration: underline;
}

.tab-body {
  display: flex;
  align-items: center;
}

.tab-box {
  flex: 1;
}

.tab-box-list {
  display: flex;
  align-items: center;
}

.examinBtn {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: red;
}

.examinBtn i {
  font-style: normal;
  color: #1b8de5;
  cursor: pointer;
  font-size: 12px;
}

.tableline .list i {
  font-style: normal;
}

.el-icon-edit-outline.priceLine {
  color: #0aa0ff;
  cursor: pointer;
}
</style>
